<template>
  <div class="app-container">
    <basic-container>
      <div class="filter-container">
        <el-button
          v-waves
          size="small"
          class="filter-item"
          type="primary"
          icon="el-icon-plus"
          @click="addRow"
        >添加</el-button>

        <el-input
          v-model="listQuery.templateName"
          size="small"
          style="width: 220px;"
          placeholder="模板名称"
          class="filter-item"
          clearable
          @keyup.enter.native="getList"
        />
        <el-button
          v-waves
          class="filter-item"
          size="small"
          type="primary"
          icon="el-icon-search"
          @click="getList"
        >搜索</el-button>
      </div>
      <el-table
        v-loading="listLoading"
        :data="list"
        border
        :height="tableHeight"
        fit
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="模板名称" width="240px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.templateName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="计费方式" width="140px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.feeType | expressFeeTypeText }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="200px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>
        <el-table-column label="修改时间" width="200px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.modifyTime }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="300" class-name="small-padding">
          <template slot-scope="scope">
            <el-button size="mini" type="success" @click="editRow(scope.row)">修改</el-button>
            <!-- <el-button size="mini" type="danger" @click="deleteRow(scope.row)">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="pagination-container">
        <el-pagination
          :current-page.sync="listQuery.page"
          :page-sizes="[10,20,30, 50]"
          :page-size="listQuery.pageSize"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div> -->

      <el-dialog  :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible" width="1150px" append-to-body>
        <el-form
          ref="dataForm"
          v-loading="isLoadingDetail"
          :rules="rules"
          :model="temp"
          label-position="left"
          label-width="140px"
          style="margin-left:50px;margin-right:50px;"
        >
          <el-form-item label="模板名称" prop="templateName">
            <el-input v-model="temp.templateName" placeholder="请输入模板名称" />
          </el-form-item>
          <el-form-item label="计费方式" prop="feeType">
            <!-- <el-radio v-model="temp.feeType" :label="0">按重量计费</el-radio> -->
            <el-radio v-model="temp.feeType" :label="1">按件计费</el-radio>
          </el-form-item>
          <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="按件计费单价" prop="feeUnit">
                    <el-input-number v-model="temp.feeUnit" placeholder="按件计费单价" style="width:160px" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                  <el-form-item label="超出单件每件费用" prop="overFeeUnit">
                      <el-input-number v-model="temp.overFeeUnit" placeholder="超出单件每件费用" style="width:160px" />
                  </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最少多少件免费" prop="freeLimitNum">
                      <el-input-number v-model="temp.freeLimitNum" placeholder="最少多少件免费" style="width:160px" />
                  </el-form-item>
              </el-col>
          </el-row>
          

          <!-- <el-form-item label="配送区域费用" prop="express_fees">
            <table style="width:100%;table-layout:fixed">
              <thead>
                <tr>
                  <th width="210" style="text-align:left">运送到</th>
                  <template v-if="temp.feeType === 0">
                    <th style="text-align:left">首重(克)</th>
                    <th style="text-align:left">首费(元)</th>
                    <th style="text-align:left">续重(克)</th>
                    <th style="text-align:left">续费(元)</th>
                  </template>
                  <template v-else>
                    <th style="text-align:left">首件(个)</th>
                    <th style="text-align:left">运费(元)</th>
                    <th style="text-align:left">续件(个)</th>
                    <th style="text-align:left">续费(元)</th>
                  </template>
                  <th width="80" />
                </tr>
              </thead>
              <tbody>
                <tr v-for="(fee,feeIndex) in temp.express_fees" :key="feeIndex">
                  <td>
                    <div v-if="fee.p==='全国'">全国(默认运费)</div>
                    <div v-else>
                      <el-select
                        v-model="fee.p"
                        placeholder="请选择省"
                        style="width:100px"
                        size="mini"
                        @change="fee.c=''"
                      >
                        <el-option
                          v-for="(_,title) in provinces"
                          :key="title"
                          :label="title"
                          :value="title"
                        />
                      </el-select>
                      <el-select
                        v-if="provinces[fee.p]"
                        v-model="fee.c"
                        placeholder="请选择城市"
                        size="mini"
                        style="width:100px"
                      >
                        <el-option
                          v-for="(_,title) in provinces[fee.p]"
                          :key="title"
                          :label="title"
                          :value="title"
                        />
                      </el-select>
                    </div>
                  </td>
                  <template v-if="temp.feeType === 0">
                    <td>
                      <el-input-number v-model="fee.fw" placeholder="首重" style="width:140px" />
                    </td>
                    <td>
                      <el-input-number v-model="fee.ff" placeholder="首费" style="width:140px" />
                    </td>
                    <td>
                      <el-input-number v-model="fee.nw" placeholder="续重" style="width:140px" />
                    </td>
                    <td>
                      <el-input-number v-model="fee.nf" placeholder="续费" style="width:140px" />
                    </td>
                  </template>
                  <template v-else>
                    <td>
                      <el-input-number v-model="fee.fw" placeholder="首件" style="width:140px" />
                    </td>
                    <td>
                      <el-input-number v-model="fee.ff" placeholder="运费" style="width:140px" />
                    </td>
                    <td>
                      <el-input-number v-model="fee.nw" placeholder="续件" style="width:140px" />
                    </td>
                    <td>
                      <el-input-number v-model="fee.nf" placeholder="续费" style="width:140px" />
                    </td>
                  </template>
                  <td>
                    <el-button
                      v-if="fee.p!=='全国'"
                      size="mini"
                      icon="el-icon-remove"
                      @click="removeExpressFee(feeIndex)"
                    >删除</el-button>
                  </td>
                </tr>
                <tr>
                  <td>
                    <el-button size="mini" icon="el-icon-plus" @click="handleAddNewAreaFee">新增配送区域</el-button>
                  </td>
                </tr>
              </tbody>
            </table>
          </el-form-item> -->
        
          <el-form-item label="付费区域" prop="feeArea">
            <div v-for="(fee,feeIndex) in temp.feeArea" :key="feeIndex">
              <el-select
                v-model="fee.p"
                placeholder="请选择省"
                style="width:100px"
                size="mini"
                filterable
                @change="fee.c=''"
              >
                <el-option
                  v-for="(_,title) in provinces"
                  :key="title"
                  :label="title"
                  :value="title"
                />
              </el-select>
              &nbsp;
              <el-select
                v-if="provinces[fee.p]"
                v-model="fee.c"
                placeholder="请选择城市"
                size="mini"
                style="width:100px"
              >
                <el-option
                  v-for="(_,title) in provinces[fee.p]"
                  :key="title"
                  :label="title"
                  :value="title"
                />
              </el-select>
              &nbsp;
              <el-button size="mini" icon="el-icon-remove" @click="removeExpressArea(feeIndex)">删除</el-button>
            </div>
            <el-button size="mini" icon="el-icon-plus" @click="handleAddNewArea">新增区域</el-button>
          </el-form-item>
          <el-form-item label="不配送区域" prop="excludeArea">
            <div v-for="(fee,feeIndex) in temp.excludeArea" :key="feeIndex">
              <el-select
                v-model="fee.p"
                placeholder="请选择省"
                style="width:100px"
                size="mini"
                filterable
                @change="fee.c=''"
              >
                <el-option
                  v-for="(_,title) in provinces"
                  :key="title"
                  :label="title"
                  :value="title"
                />
              </el-select>
              &nbsp;
              <el-select
                v-if="provinces[fee.p]"
                v-model="fee.c"
                placeholder="请选择城市"
                size="mini"
                filterable
                clearable
                style="width:100px"
              >
                <el-option
                  v-for="(_,title) in provinces[fee.p]"
                  :key="title"
                  :label="title"
                  :value="title"
                />
              </el-select>
              &nbsp;
              <el-button size="mini" icon="el-icon-remove" @click="removeNotExpressArea(feeIndex)">删除</el-button>
            </div>
            <el-button size="mini" icon="el-icon-plus" @click="handleAddNewNotArea">新增区域</el-button>
          </el-form-item>
        </el-form>

          
        
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button :loading="isSubmiting" type="primary" @click="submitFormAction">确定</el-button>
        </div>
      </el-dialog>
    </basic-container>
  </div>
</template>

<script>
import {
  memberLevelTextEnum,
  expressFeeTypeTextEnum
} from "../../constants/constants";
// import * as apiObj from "@/api/expressTemplate";
export default {
  filters: {
    memberLevel(level) {
      return memberLevelTextEnum[level];
    },
    expressFeeTypeText(v) {
      return expressFeeTypeTextEnum[v];
    }
  },
  data() {
    return {
      list: null,
      isSubmiting: false,
      provinces: [],
      tableHeight: 0,
      isEditing: false,
      memberLevelTextEnum,
      dialogFormVisible: false,
      expressFeeTypeTextEnum,
      pwdDialogFormVisible: false,
      listLoading: true,
      temp: {
        templateName: "",
        feeType: 1,
        feeUnit:0,
        overFeeUnit:0,
        freeLimitNum:0,
        excludeArea:[],
        feeArea:[]
      },
      total: 0,
      isLoadingDetail:false,
      rules: {
        templateName: [
          {
            required: true,
            message: "模板名称不能为空",
            trigger: "change"
          }
        ],
        feeType: [
          {
            required: true,
            message: "请选择计费方式",
            trigger: "change"
          }
        ],
        feeUnit: [
          {
            required: true,
            message: "请填写单件商品费用",
            trigger: "change",
            type: "number"
          }
        ],
        overFeeUnit: [
          {
            required: true,
            message: "超出单件每件费用",
            trigger: "change"
          }
        ],
        freeLimitNum: [
          {
            required: true,
            message: "请填写免费条件",
            trigger: "change"
          }
        ]
      },
      listQuery: {
        username: "",
        page: 1,
        pageSize: 10
      }
    };
  },
  computed: {
    currentProvinces() {
      const titles = this.temp.express_fees.map(e => e.p);
      return this.provinces.filter(el => titles.indexOf(el.title) == -1);
    }
  },
  created() {
    this.getList();
    this.loadProvinces();
    this.tableHeight = window.innerHeight - 220;
  },
  methods: {
    removeExpressFee(feeIndex) {
      this.temp.express_fees.splice(feeIndex, 1);
    },
    removeExpressArea(idx) {
      this.temp.feeArea.splice(idx, 1);
    },
    removeNotExpressArea(idx){
      this.temp.excludeArea.splice(idx, 1);
    },
    handleAddNewArea() {
      this.temp.feeArea.push({
        p: "",
        c: ""
      });
    },
    handleAddNewNotArea() {
      this.temp.excludeArea.push({
        p: "",
        c: ""
      });
    },
    handleAddNewAreaFee() {
      this.temp.express_fees.push({
        p: "",
        c: "",
        fw: 1000, // 首重
        ff: 0, // 首费,
        nw: 1000, // 续重
        fe: 0,
        nf: 0 // 续费
      });
    },
    loadProvinces() {
      this.$service.area.queryData().then(data => {
        this.provinces = data;
      });
    },
    submitPwdFormAction() {
      this.$refs.pwdForm.validate(valid => {
        if (valid) {
          this.isSubmiting = true;
          this.$api
            .post(this.$urls.admin.changePwd, {
              id: this.temp.id,
              newPwd: this.temp.password
            })
            .then(res => {
              this.success();
              this.pwdDialogFormVisible = false;
            })
            .finally(_ => {
              this.isSubmiting = false;
            });
        }
      });
    },
    deleteRow(row) {
      this.confirm("确认删除该记录吗").then(_ => {
        this.$service.expressTemplate.remove(row.id).then(_ => {
          this.success();
          this.getList();
        });
      });
    },
    addRow() {
      this.dialogFormVisible = true;
      this.isEditing = false;
      Object.keys(this.temp).forEach(key => {
        if (Array.isArray(this.temp[key])) {
          this.temp[key] = [];
        } else {
          if(key == 'feeType') {
            this.temp[key] = 1;
          } else if(key == 'templateName') {
            this.temp[key] = "";
          } else {
            this.temp[key] = 0;
          }
        }
      });
      // this.temp.express_fees.push({
      //   p: "全国",
      //   fw: 1000, // 首重
      //   ff: 0, // 首费,
      //   nw: 1000, // 续重
      //   nf: 0, // 续费
      //   fe: 0
      // });
    },
    editRow(row) {
      this.dialogFormVisible = true;
      this.isEditing = true;
      this.isLoadingDetail = true;
      this.$service.expressTemplate.detail(row.id).then(data=>{
        data.excludeArea = this.parseAreaValueToArr(data.excludeArea)
        data.feeArea = this.parseAreaValueToArr(data.feeArea)
        this.temp = data;
      }).finally(()=>{
        this.isLoadingDetail = false;
      });
    },
    handleCurrentChange(page) {
      this.listQuery.page = page;
      this.getList();
    },
    handleSizeChange(size) {
      this.listQuery.pageSize = size;
      this.getList();
    },
    getList() {
      this.listLoading = true;
      this.$service.expressTemplate
        .list(this.listQuery)
        .then(response => {
          this.list = response || [];
          // this.total = response.total;
        })
        .finally(_ => {
          this.listLoading = false;
        });
    },
    validPostData(postData) {
      let map = {};
      for (let i = 0, l = postData.feeArea.length; i < l; i++) {
        const v = postData.feeArea[i];
        if (!v.p) {
          this.$message.error("请选择付费省份");
          return false;
        }
        // if (this.provinces[v.p] && !v.c) {
        //   this.$message.error("请选择付费城市");
        //   return false;
        // }   
        if(map[v.p + '-' + v.c]){
          this.$message.error("付费区域重复：" + v.p + ' ' + v.c);
          return false;
        }    
        map[v.p + '-' + v.c] = true;
      }
      map = {};
      if (postData.excludeArea && postData.excludeArea.length) {
        for (let i = 0, l = postData.excludeArea.length; i < l; i++) {
          const v = postData.excludeArea[i];
          if (!v.p) {
            this.$message.error("请选择不配送省份");
            return false;
          }
          // if (this.provinces[v.p] && !v.c) {
          //   this.$message.error("请选择不配送城市");
          //   return false;
          // }
          if(map[v.p + '-' + v.c]){
            this.$message.error("不配送区域重复：" + v.p + ' ' + v.c);
            return false;
          }    
          map[v.p + '-' + v.c] = true;
        }
      }
      return true;
    },
    parseAreaValue(area){
      const results = {};
      for(const {p ,c } of area) {
          results[p] = results[p] || [];
          if(c) {
            results[p].push(c);
          }
      }
      return JSON.stringify(Object.keys(results).reduce((a,b)=>(a.push({[b]:results[b]}),a),[]));
    },
    // 转换成数组
    parseAreaValueToArr(area){
      if(typeof area === 'string'){
        area = JSON.parse(area);
      }
      const results = [];
      for(const a of area) {
          Object.keys(a).forEach(k=>{
            if(!a[k].length) {
              results.push({
                p:k,
                c:''
              });
              return;
            } 
            a[k].forEach(j=>{
              const item = {};
              item.p = k;
              item.c = j;
              results.push(item);
            });
          });
      }
      return results;
    },
    submitFormAction() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (!this.validPostData(this.temp)) {
            return;
          }
          this.isSubmiting = true;
          const func = this.isEditing
            ? this.$service.expressTemplate.update
            : this.$service.expressTemplate.create;
          const postData = { ...this.temp };

          postData.excludeArea = this.parseAreaValue(postData.excludeArea);
          postData.feeArea = this.parseAreaValue(postData.feeArea);
          
          func(postData)
            .then(res => {
              this.success();
              this.dialogFormVisible = false;
              this.getList();
            })
            .finally(_ => {
              this.isSubmiting = false;
            });
        }
      });
    }
  }
};
</script>
